package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallGrouponMapper;
import org.linlinjava.litemall.db.dao.LitemallSpellMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.GrouponConstant;
import org.linlinjava.litemall.db.util.OrderSpellConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.SpellConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallSpellService {
    @Resource
    private LitemallSpellMapper mapper;

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderService orderService;

    /**
     * 创建或参与一个拼团
     *
     * @param spell
     * @return
     */
    public int create(LitemallSpell spell) {
        spell.setAddTime(LocalDateTime.now());
        spell.setUpdateTime(LocalDateTime.now());
        return mapper.insertSelective(spell);
    }

    /**
     * 更新
     *
     * @param spell
     * @return
     */
    public int updateById(LitemallSpell spell) {
        spell.setUpdateTime(LocalDateTime.now());
        return mapper.updateByPrimaryKeySelective(spell);
    }

    /**
     * 根据订单id查询参加的拼单
     *
     * @param orderId
     * @return
     */
    public LitemallSpell queryByOrderId(Integer orderId) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);
        return mapper.selectOneByExample(example);
    }

    /**
     * 根据订单id查询发起的拼单
     *
     * @param orderId
     * @return
     */
    public LitemallSpell queryInitiatorByOrderId(Integer orderId) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andOrderIdEqualTo(orderId).andSpellIdEqualTo(0).andDeletedEqualTo(false);
        return mapper.selectOneByExample(example);
    }

    /**
     * 根据订单id查询参与的拼单
     *
     * @param orderId
     * @return
     */
    public LitemallSpell queryInvolveByOrderId(Integer orderId) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andOrderIdEqualTo(orderId).andSpellIdNotEqualTo(0).andStatusNotEqualTo(SpellConstant.STATUS_FAIL).andDeletedEqualTo(false);
        return mapper.selectOneByExample(example);
    }

    /**
     * 查询参与者
     *
     * @param linkId
     * @return
     */
    public LitemallSpell queryJoinRecord(Integer linkId) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andSpellIdEqualTo(linkId).andStatusNotEqualTo(SpellConstant.STATUS_FAIL).andDeletedEqualTo(false);
        return mapper.selectOneByExample(example);
    }

    /**
     * 查询参与者
     *
     * @param linkId
     * @return
     */
    public List<LitemallSpell> queryAllJoinRecord(Integer linkId) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andSpellIdEqualTo(linkId).andDeletedEqualTo(false);
        return mapper.selectByExample(example);
    }

    /**
     * 根据userId 和 id查询
     *
     * @param userId
     * @param id
     * @return
     */
    public LitemallSpell queryById(Integer userId, Integer id) {
        LitemallSpellExample example = new LitemallSpellExample();
        example.or().andUserIdEqualTo(userId).andIdEqualTo(id).andDeletedEqualTo(false);
        return mapper.selectOneByExample(example);
    }

    /**
     * 根据userId查询我的开单
     *
     * @param userId
     * @return
     */
    public List<LitemallSpell> queryStartSpell(Integer userId, Integer page, Integer limit, String sort, String order) {
        LitemallSpellExample example = new LitemallSpellExample();
        LitemallSpellExample.Criteria criteria = example.or();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId).andCreatorUserIdEqualTo(userId);
        }
        criteria.andSpellIdEqualTo(0).andDeletedEqualTo(false);
        if (!org.springframework.util.StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        return mapper.selectByExample(example);
    }

    /**
     * 根据userId查询我参与的拼单
     *
     * @param userId
     * @return
     */
    public List<LitemallSpell> queryJoinSpell(Integer userId, Integer page, Integer limit, String sort, String order) {
        LitemallSpellExample example = new LitemallSpellExample();
        LitemallSpellExample.Criteria criteria = example.or();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        criteria.andSpellIdNotEqualTo(0).andDeletedEqualTo(false);
        if (!org.springframework.util.StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        return mapper.selectByExample(example);
    }

    /**
     * 检查过期的拼单
     * @return
     */
    public List<LitemallSpell> queryExpired() {
        LitemallSpellExample example = new LitemallSpellExample();
        LitemallSpellExample.Criteria criteria = example.or();
        criteria.andDeletedEqualTo(false).andSpellIdEqualTo(0).andExpireTimeLessThan(LocalDateTime.now()).andStatusNotEqualTo(SpellConstant.STATUS_FAIL).andStatusNotEqualTo(SpellConstant.STATUS_SUCCESS);
        return mapper.selectByExample(example);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    public LitemallSpell findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }


    /**
     * 拼单失败
     *
     * @param creator
     */
    public void fail(LitemallSpell creator) {
        if (creator.getStatus().equals(SpellConstant.STATUS_FAIL)) { // 如果已经失败就不处理
            return;
        }
        // 发起者失败
        creator.setStatus(SpellConstant.STATUS_FAIL);
        updateById(creator);
        // 发起者订单标记失败
        LitemallOrder order = orderService.findById(creator.getOrderId());
        order.setSpellStatus(OrderSpellConstant.STATUS_NO);
        orderService.updateWithOptimisticLocker(order);
        // 所有参与者失败
        List<LitemallSpell> joiners = queryAllJoinRecord(creator.getId());
        for (LitemallSpell joiner : joiners) {
            if (!joiner.getStatus().equals(SpellConstant.STATUS_FAIL)) {
                joiner.setStatus(SpellConstant.STATUS_FAIL);
                joiner.setEndTime(LocalDateTime.now());
                updateById(joiner);
                // 参与者订单如果未支付标记失败
                LitemallOrder joinerOrder = orderService.findById(joiner.getOrderId());
                if (joinerOrder.getOrderStatus().equals(OrderUtil.STATUS_CREATE)) { // 订单待付款
                    joinerOrder.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
                    orderService.updateWithOptimisticLocker(joinerOrder);
                }
            }
        }
    }
}
